package com.example.mall_image_server.service;

import com.example.mall_image_server.utils.FileMd5Utils;
import com.example.mall_image_server.utils.FileUploadUtils;
import com.example.mall_image_server.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LocalFileUploadServiceImpl implements FileUploadService {
    @Value("${upload.image.image-origin-base-path}") // 图片服务器的基本地址,用于拼接可访问的远程图片地址 -> 返回给请求方
    private String imageOriginBasePath;
    @Value("${upload.image.image-server-path}")
    private String localImagePath;
    private String imgRedisPrefix = "img-";

    /**
     * 单图处理
     * @param file
     * @return
     */
    @Override
    public String saveImage(MultipartFile file) {
        // 图片校验
        if (!FileUploadUtils.checkImage(file)) {
            return "";
        }

        // 文件名 和 写入的目录
        try {
            String fileM5d = FileMd5Utils.calcMD5(file.getInputStream());
            // 查询redis记录是否存在该文件对应的地址?
            if (RedisUtils.hasKey(imgRedisPrefix + fileM5d)) {
                System.out.println("存在");
                String url = (String) RedisUtils.get(imgRedisPrefix + fileM5d);
                return url;
            }

            String originName = file.getOriginalFilename();
            String fileSuffix = originName.substring(originName.lastIndexOf("."));
            String originFileName = fileM5d + fileSuffix;
            String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/";
            String filePath = localImagePath + datePath;
            File createFilePath = new File(filePath);
            if (!createFilePath.exists()) // 创建由日期时间划分的文件目录
                createFilePath.mkdirs();

            String filePathName = filePath + originFileName;
            // 根据地址写入图片
            BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(
                            new File(filePathName)));
            try {
                out.write(file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.flush();
            out.close();

            System.out.println("写入文件,并记录");
            String imgOriginUrl = imageOriginBasePath + datePath + originFileName;
            // 保存成功,记录进redis
            RedisUtils.set(imgRedisPrefix+fileM5d, imgOriginUrl);

            return imgOriginUrl;
        } catch (FileNotFoundException e) {
            throw new RuntimeException("上传失败: "+e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException("上传失败: "+e.getMessage());
        }
    }

    /**
     * 多图上传
     * @param files
     * @return
     */
    public List<String> saveImages(MultipartFile[] files) {
        // 开启多线程处理
        // TODO
        if (files.length <= 0) {
            // throw new RuntimeException("没传文件");
            return null;
        }

        List<String> urls = new ArrayList<>();
        for (int i=0; i < files.length; i++) {
            if (!files[i].isEmpty()) {
                String url =saveImage(files[i]);
                urls.add(url);
            }
        }

        return urls;
    }
}
